'use strict';
const {redis_set_ads} =  require('../../../utils/init')
const BaseController = require('../../core/base_controller');

class AdsController extends BaseController {
  // 获取广告列表
  async index() {
    const { ctx } = this;
    const { page = 1, pageSize = 10, title, type, status } = ctx.query;

    const where = { del_flag: 0 };
    if (title) where.title = { [ctx.model.Sequelize.Op.like]: `%${title}%` };
    if (type) where.type = type;
    if (status !== undefined) where.status = parseInt(status);

    const { count, rows } = await ctx.model.Ads.findAndCountAll({
      where,
      order: [['created_at', 'DESC']],
      offset: (page - 1) * pageSize,
      limit: parseInt(pageSize),
      attributes: { exclude: ['del_flag'] }
    });

    this.success({
      list: rows,
      pagination: {
        total: count,
        current: parseInt(page),
        pageSize: parseInt(pageSize),
      },
    });
  }

  // 创建广告
  async create() {
    const { ctx } = this;

    const rules = {
      title: { type: 'string', required: true, message: '请输入广告标题' },
      type: { type: 'string', required: true, message: '请输入广告类型' },
      href: { type: 'string', required: false },
      img: { type: 'string', required: false, message: '请上传广告图片' },
      status: { type: 'enum', values: [0, 1], required: false, default: 1 },
    };

    try {
      ctx.validate(rules);
    } catch (err) {
      const errors = err.errors.map(error => rules[error.field].message).join(', ');
      ctx.throw(400, errors);
    }

    const ads = await ctx.model.Ads.create(ctx.request.body);
    redis_set_ads(ctx.app)
    this.success(ads, '创建成功');
  }

  // 更新广告
  async update() {
    const { ctx } = this;
    const id = ctx.params.id;

    const rules = {
      title: { type: 'string', required: false },
      type: { type: 'string', required: false },
      href: { type: 'string', required: false },
      img: { type: 'string', required: false },
      status: { type: 'enum', values: [0, 1], required: false },
    };

    try {
      ctx.validate(rules);
    } catch (err) {
      const errors = err.errors.map(error => rules[error.field].message).join(', ');
      ctx.throw(400, errors);
    }

    const ads = await ctx.model.Ads.findByPk(id);
    if (!ads) {
      ctx.throw(404, '广告不存在');
    }

    await ads.update(ctx.request.body);
    redis_set_ads(ctx.app)
    this.success(ads, '更新成功');
  }

  // 删除广告
  async destroy() {
    const { ctx } = this;
    const id = ctx.params.id;

    const ads = await ctx.model.Ads.findByPk(id);
    if (!ads) {
      ctx.throw(404, '广告不存在');
    }

    await ads.update({ del_flag: 1 });
    redis_set_ads(ctx.app)
    this.success(null, '删除成功');
  }

  // 修改状态
  async updateStatus() {
    const { ctx } = this;
    const { id } = ctx.params;

    const rules = {
      status: {
        type: 'enum',
        values: [0, 1],
        required: true,
        message: '状态值无效，应为：0-禁用，1-启用'
      },
    };

    try {
      ctx.validate(rules);
    } catch (err) {
      const errors = err.errors.map(error => rules[error.field].message).join(', ');
      ctx.throw(400, errors);
    }

    const ads = await ctx.model.Ads.findByPk(id);
    if (!ads) {
      ctx.throw(404, '广告不存在');
    }

    await ads.update({ status: ctx.request.body.status });
    redis_set_ads(ctx.app)
    this.success(null, '状态更新成功');
  }
}

module.exports = AdsController;
